//
//  UrlArticleViewController.m
//  Behing
//
//  Created by Lj on 2017/12/28.
//  Copyright © 2017年 lj. All rights reserved.
//

#import "UrlArticleViewController.h"
#import <WebKit/WebKit.h>
#import "BHPhotoBrowser.h"

@interface UrlArticleViewController ()<WKUIDelegate,WKNavigationDelegate>
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) NSArray *dataArray;

@end

@implementation UrlArticleViewController

#pragma mark - Lazy
- (WKWebView *)webView {
    if (_webView == nil) {
        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, App_Frame_Width, App_Frame_Height - kNavbarAndStatusBar)];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        [self.view addSubview:_webView];
    }
    return _webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"详情";
    
    [[BHAlertUtil alertManager]showLoadingView:self.webView];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]]];
    [self initNavBarBackBtn];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    [[BHAlertUtil alertManager]hiddenLoading];
    [self getImageUrlByJS:webView imageArray:^(NSArray *image) {
        self.dataArray = image;
    }];
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation {
    [[BHAlertUtil alertManager]hiddenLoading];
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(nonnull WKNavigationAction *)navigationAction decisionHandler:(nonnull void (^)(WKNavigationActionPolicy))decisionHandler {
    [self showBigImage:navigationAction.request];
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)getImageUrlByJS:(WKWebView *)wkWebView imageArray:(void(^)(NSArray *))imageArray {
    //查看大图代码
    //js方法遍历图片添加点击事件返回图片个数
    static  NSString * const jsGetImages =
    @"function getImages(){\
    var objs = document.getElementsByTagName(\"img\");\
    var imgUrlStr ='';\
    for(var i = 0;i < objs.length; i++){\
    if(i == 0){\
    if(objs[i].alt==''){\
    imgUrlStr=objs[i].src;\
    }\
    }else{\
    if(objs[i].alt==''){\
    imgUrlStr+='#'+objs[i].src;\
    }\
    }\
    objs[i].onclick=function(){\
    if(this.alt==''){\
    document.location=\"myweb:imageClick:\"+this.src;\
    }\
    };\
    };\
    return imgUrlStr;\
    };";
    
    //用js获取全部图片
    [self.webView evaluateJavaScript:jsGetImages completionHandler:^(id Result, NSError * error) {
    }];
    
    NSString *js2 = @"getImages()";
    __block NSArray *array = [NSArray array];
    [wkWebView evaluateJavaScript:js2 completionHandler:^(id Result, NSError * error) {
        NSString *resurlt=[NSString stringWithFormat:@"%@",Result];
        if([resurlt hasPrefix:@"#"]) {
            resurlt=[resurlt substringFromIndex:1];
        }
        array = [resurlt componentsSeparatedByString:@"#"];
        imageArray(array);
    }];
}


- (BOOL)showBigImage:(NSURLRequest *)request {
    //将url转换为string
    NSString *requestString = [[request URL] absoluteString];
    //hasPrefix 判断创建的字符串内容是否以pic:字符开始
    if ([requestString hasPrefix:@"myweb:imageClick:"]) {
        NSString *imageUrl = [requestString substringFromIndex:@"myweb:imageClick:".length];
        NSInteger index = 0;
        for (NSInteger i = 0; i < [self.dataArray count]; i++) {
            if([imageUrl isEqualToString:self.dataArray[i]]) {
                index = i;
                break;
            }
        }
        BHPhotoBrowser *photoBrower = [[BHPhotoBrowser alloc]initWithImages:self.dataArray currentIndex:index];
        [self pushViewController:photoBrower animated:YES];
        return NO;
    }
    return YES;
}


@end
